package juc.Lock.readwriteLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

import static juc.Sleep.sleep;

/**
 * @author 况祥彬
 * @date 2020/12/14 15:15
 **/
@Slf4j
public class TestReentrantReadWriteLock {
    Object data;
    private ReentrantReadWriteLock rw=new ReentrantReadWriteLock();
    //获取读锁
    private ReentrantReadWriteLock.ReadLock r= rw.readLock();
    //获取写锁
    private ReentrantReadWriteLock.WriteLock w= rw.writeLock();


    public Object read() {
        log.debug("获取读锁...");
        r.lock();
        try {
            log.debug("获取到锁，读取");
            sleep(1);
            return data;
        } finally {
            log.debug("释放读锁...");
            r.unlock();
        }
    }

    public void write() {
        log.debug("获取写锁...");
        w.lock();
        try {
            log.debug("获取到锁，写入");
            sleep(1);
        } finally {
            log.debug("释放写锁...");
            w.unlock();
        }
    }

    public static void main(String[] args) {
        TestReentrantReadWriteLock d = new TestReentrantReadWriteLock();
        new Thread(()->{
            d.read();
        },"t1").start();
        new Thread(()->{
            d.read();
        },"t2").start();

    }

}
